package com.sky.service.user.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    private static Long id = 1L;
    @Autowired
    private  WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private  JwtProperties jwtProperties;
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //调用微信方法获取openid
        /*String openId = getOpenId(userLoginDTO.getCode());
        if(StringUtils.isEmpty(openId)){
            throw new RuntimeException("登录失败");
        }*/
        //调用mapper层
        User user = userMapper.selectByOpenId("osvjO5VXi2ghcPu68RvVdwHWskjA");
        //判断是否存在该openid对应的用户信息，没有则创建用户
        if(user==null){
            user = User.builder()
                    .openid("osvjO5VXi2ghcPu68RvVdwHWskjA")
                    .createTime(LocalDateTime.now())
                    .build();
            //调用方法添加新用户信息
            userMapper.save(user);
        }
            //如果有，则根据ID生成token返回
            Map<String ,Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID,user.getId());
            String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //查询商家信息
        Merchant merchant = userMapper.selectById(id);
        //计算配送费
            //调用方法，根据商家地理位置获取商家经纬度坐标
        String merString = MapUtils.addressToLnglat(merchant.getShopAddress());
            //调用方法，根据商家经纬度和用户经纬度坐标，计算出配送费用
        String userLocation = /*userLoginDTO.getLocation();*/"116.481488,39.990464";
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(merString, userLocation);
        //构建返回信息
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid("osvjO5VXi2ghcPu68RvVdwHWskjA")
                .token(token)
                .shopAddress(merchant.getShopAddress())
                .shopId(merchant.getId())
                .deliveryFee(delivoryCost)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .build();
        return userLoginVO;
    }

    public String getOpenId(String code){
        Map<String ,String> map = new HashMap<>();
        map.put("appId",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String jsonStr =  HttpClientUtil.doGet(WX_LOGIN,map);
        Map res = JSON.parseObject(jsonStr, Map.class);
        return res.get("openid").toString();

    }


    @Override
    public int save(User user) {
        int save = userMapper.save(user);
        return save;
    }
}
